<template>
  <div>



    <div style="margin-bottom: 20px">
      <el-input
          style="width: 240px"
          placeholder="请输入害虫名称"
          v-model="params.name"
          clearable
          @clear="load"
      ></el-input>

      <el-input
          style="width: 240px; margin-left: 5px"
          placeholder="请输入分类"
          v-model="params.category"
          clearable
          @clear="load"
      ></el-input>

      <el-button
          style="margin-left: 5px"
          type="primary"
          icon="el-icon-search"
          @click="load"
      >搜索</el-button>

      <el-button
          style="margin-left: 5px"
          type="warning"
          icon="el-icon-refresh"
          @click="reset"
      >重置</el-button>
    </div>

    <!-- 表格 -->
    <el-table :data="tableData" stripe row-key="id" style="width: 100%">
      <el-table-column label="编号" width="80">
        <template slot-scope="scope">
          {{ (params.pageNum - 1) * params.pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column prop="name" label="害虫名称" min-width="160" />
      <el-table-column prop="category" label="分类" width="120" />

      <el-table-column prop="livingHabits" label="生活习性" min-width="200" show-overflow-tooltip>
        <template slot-scope="scope">
          {{ fixField(scope.row.livingHabits) }}
        </template>
      </el-table-column>

      <el-table-column prop="controlMethods" label="防治方法" min-width="220" show-overflow-tooltip>
        <template slot-scope="scope">
          {{ fixField(scope.row.controlMethods) }}
        </template>
      </el-table-column>

      <el-table-column label="操作" width="220" fixed="right">
        <template slot-scope="scope">
          <el-button
              type="text"
              size="mini"
              @click="viewDetail(scope.row.id)"
          >详情</el-button>

          <el-button
              type="primary"
              size="mini"
              @click="$router.push('/editPest?id=' + scope.row.id)"
          >编辑</el-button>

          <el-popconfirm
              style="margin-left: 8px"
              title="您确定删除这行数据吗？"
              @confirm="del(scope.row.id)"
          >
            <el-button slot="reference" type="danger" size="mini">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div style="margin-top: 20px; text-align: right">
      <el-pagination
          background
          layout="prev, pager, next"
          :current-page="params.pageNum"
          :page-size="params.pageSize"
          :total="total"
          @current-change="handleCurrentChange"
      />
    </div>

    <!-- 详情弹窗 -->
    <el-dialog
        :title="detail.title"
        :visible.sync="detail.visible"
        width="700px"
        top="5vh"
        :close-on-click-modal="false"
    >
      <el-form label-width="110px" v-if="detail.data">
        <el-row :gutter="12">
          <el-col :span="12">
            <el-form-item label="编号：">
              <span>{{ detail.data.id }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="名称：">
              <span>{{ detail.data.name }}</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="分类：">
          <el-tag size="small" :type="getTagType(detail.data.category)">
            {{ detail.data.category || '暂无' }}
          </el-tag>
        </el-form-item>

        <!-- 图片展示区域 -->
        <el-form-item label="害虫图片：">
          <div v-if="detail.data && detail.data.cover && detail.data.cover.length > 0" class="image-gallery">
            <el-image
                v-for="(img, index) in detail.data.cover"
                :key="index"
                :src="img"
                :preview-src-list="detail.data.cover.map(url => url + (url.includes('?') ? '&' : '?') + 'preview=true')"
                class="image-item"
                fit="cover"
                lazy>
              <div slot="error" class="image-slot">
                <i class="el-icon-picture-outline"></i>
                <div>图片加载失败</div>
              </div>
            </el-image>
          </div>
          <div v-else class="no-image">
            暂无图片
          </div>
        </el-form-item>

        <el-form-item label="基本信息：">
          <div class="pre-line">{{ detail.data.basicInformation || '暂无' }}</div>
        </el-form-item>

        <el-form-item label="形态特征：">
          <div class="pre-line">{{ detail.data.morphologicalCharacteristics || '暂无' }}</div>
        </el-form-item>

        <el-form-item label="生活习性：">
          <div class="pre-line">{{ detail.data.livingHabits || '暂无' }}</div>
        </el-form-item>

        <el-form-item label="发生规律：">
          <div class="pre-line">{{ detail.data.occurrencePattern || '暂无' }}</div>
        </el-form-item>

        <el-form-item label="危害特点：">
          <div class="pre-line">{{ detail.data.hazardCharacteristics || '暂无' }}</div>
        </el-form-item>

        <el-form-item label="防治方法：">
          <div class="pre-line">{{ detail.data.controlMethods || '暂无' }}</div>
        </el-form-item>
      </el-form>

      <span slot="footer">
        <el-button @click="detail.visible = false">关 闭</el-button>
      </span>
    </el-dialog>

    <!-- 上传图片弹窗 -->
    <el-dialog
        title="上传图片"
        :visible.sync="uploadDialogVisible"
        width="400px"
        top="30vh"
        :close-on-click-modal="false"
    >
      <el-upload
          ref="upload"
          action=""
          :auto-upload="false"
          :on-change="handleChange"
          :on-remove="handleRemove"
          :file-list="fileList"
          :limit="1"
          :on-exceed="handleExceed"
          accept="image/*"
      >
        <el-button slot="trigger" type="primary">选取文件</el-button>
        <el-button type="success" @click="confirmUpload">上传到服务器</el-button>
        <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
      </el-upload>

      <span slot="footer">
        <el-button @click="uploadDialogVisible = false">关 闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request'

export default {
  name: 'PestList',

  data() {
    return {
      tableData: [],
      total: 0,
      params: {
        pageNum: 1,
        pageSize: 10,
        name: '',
        category: ''
      },
      detail: {
        visible: false,
        title: '',
        data: null
      },
      uploadDialogVisible: false,
      selectedFile: null,
      fileList: [],
      imageUrl: ''
    }
  },
  created() {
    this.load()
  },
  methods: {
    /* ---------- 数据 ---------- */
    load() {
      request.get('/pest/page', { params: this.params }).then(res => {
        if (res.code === '200') {
          this.tableData = res.data.list
          this.total = res.data.total
        }
      })
    },
    reset() {
      this.params = { pageNum: 1, pageSize: 10, name: '', category: '' }
      this.load()
    },
    handleCurrentChange(pageNum) {
      this.params.pageNum = pageNum
      this.load()
    },
    /* ---------- 删除 ---------- */
    del(id) {
      request.delete('/pest/delete/' + id).then(res => {
        if (res.code === '200') {
          this.$message.success('删除成功')
          this.load()
        } else {
          this.$message.error(res.msg || '删除失败')
        }
      })
    },
    /* ---------- 详情 ---------- */
    viewDetail(id) {
      request.get(`/pest/${id}`).then(res => {
        if (res.code === '200') {
          this.detail.data = res.data
          this.detail.title = `害虫详情 - ${res.data.name}`
          this.detail.visible = true

          // 拉取图片地址（字符串数组）
          request.get(`/image/list/${id}`).then(imgRes => {
            let urlList = []
            if (imgRes.code === '200' && Array.isArray(imgRes.data)) {
              urlList = imgRes.data   // 后端返回的就是字符串数组
            }
            this.$set(this.detail.data, 'cover', urlList)
            console.log('图片地址已转换：', urlList)
          }).catch(() => {
            this.$set(this.detail.data, 'cover', [])
          })
        } else {
          this.$message.error(res.msg || '获取详情失败')
        }
      }).catch(error => {
        console.error('获取害虫详情失败:', error)
        this.$message.error('获取详情失败: ' + error.message)
      })
    },

    /* ---------- 工具 ---------- */
    getTagType(category) {
      const map = {
        '蜱螨目': 'danger',
        '膜翅目': 'warning',
        '双翅目': 'danger',
        '缨翅目': 'success',
        '直翅目': 'danger',
        '同翅目/半翅目（刺吸类）': 'warning',
        '半翅目': 'danger',
        '鳞翅目': 'success',
        '鞘翅目': 'danger'
      }
      return map[category] || 'info'
    },
    fixField(val) {
      if (!val || val === 'null') return '暂无数据'
      return val
          .replace(/contro1Methods/g, 'controlMethods')
          .replace(/1ivingHabits/g, 'livingHabits')
    },

    /* ---------- 上传 ---------- */
    handleChange(file, fileList) {
      this.selectedFile = file
      this.fileList = fileList
    },
    handleRemove(file, fileList) {
      this.selectedFile = null
      this.fileList = fileList
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },
    async confirmUpload() {
      if (!this.selectedFile) return

      // 1. 创建空记录
      const saveResp = await request.post('/pest/save', {
        name: '待识别',
        category: '未知',
        livingHabits: '',
        morphologicalCharacteristics: '',
        controlMethods: ''
      })
      if (saveResp.code !== '200') {
        this.$message.error('创建记录失败')
        return
      }
      const pestId = saveResp.data

      // 2. 上传图片
      const formData = new FormData()
      formData.append('file', this.selectedFile.raw) // 改为'files'以匹配后端@RequestParam("files")
      const upResp = await request.post(`/image/upload/${pestId}`, formData)
      if (upResp.code === '200') {
        this.imageUrl = upResp.data[0]
        this.$message.success('上传成功')
        this.uploadDialogVisible = false
        this.load() // 重新加载
      } else {
        this.$message.error('图片上传失败')
      }
    }
  }
}
</script>
